#include "tcp.h"


//套接字初始化
int socketInit(char *ip, char *port, bool serverflag){

	int sockfd;
	Addr_in addr;

	func_socket fun = serverflag ? bind : connect;

	//创建套接字 IPV4 TCP
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		ErrorExit("socket");
	}

	//3.设置地址可重用
	if(serverflag){

		int reuse = 1;
		if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0){
			ErrorExit("setsockopt");
		}
	}

	//绑定通信结构体
	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(port));
	if(inet_aton(ip, &addr.sin_addr) == 0){
		ErrorExit("inet_aton");
	}
	
	if(fun(sockfd, (Addr *)&addr, sizeof(Addr_in)) < 0){
		ErrorExit("bind");
	}

	//监听套接字
	if(serverflag){

		if(listen(sockfd, 5) < 0){
			ErrorExit("listen");
		}
	}
	return sockfd;
}
//读取本地文件配置
void readConfig(char *buff, FILE *fp, char **ip, char **port){
	
	//读取本地文件配置
	if(fp == NULL){
		ErrorExit("fopen");
	}
	//读取IP配置
	*ip = fgets(buff, 100, fp);
	buff[strlen(buff)-1] = '\0';
	*port = fgets(buff+100, 100, fp);
	buff[100 + strlen(buff+100) - 1] = '\0';
}
//socket数据传输
int socketTransport(int sockfd, char * buff, size_t len, func_socket_data fun){
	int ret;
	char * s = fun == read ? "read" : "write";
	do{
		ret = fun(sockfd, buff, len);
	}while(ret < 0 && errno == EINTR);
	if(ret < 0){
		ErrorExit(s);
	}
	return ret;
}
